有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在JpaRepository findAll()方法中返回对象的浅拷贝

我试图使用JpaRepositoryfindAll()方法检索实体列表,但我试图检索的实体中有许多其他对象作为OneToMany关系

我有一个类Program,如下所示:

@Entity
public class Program extends BaseEntity {

    private String programTitle;

    private String description;

    private String programType;

    private String price;

    @OneToMany(mappedBy = "program", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    @JsonManagedReference(value = "program-benefit")
    private List<Benefit> benefits = new ArrayList<>();

    @Column(name = "category")
    private String category;
    //Getters and setters
    }

如您所见,它有一个Benefits列表

当我试图检索程序时,我得到一个JSON,其中同时包含对象列表,如:

我得到的回应:

{
    "id":1,
    "category": "cardio",
    "description": "exercies for cardio",
    "benefit": [
        {
            "description": "good for healt"
        },
        {
            "description": "string2"
        }
    ],
    "price": "50",
    "program_title": "cardio demo"
}

但我想要一个像这样的物体的浅拷贝

预期响应:

{
    "id":1,
    "category": "cardio",
    "description": "exercies for cardio",
    "price": "50",
    "program_title": "cardio demo"
}

我尝试更改CascadeType,但它会停止在所有API中显示嵌套对象,我只希望在调用findAll()方法时删除嵌套对象

当我调用findAll()方法时,有没有办法停止显示嵌套对象


共 (1) 个答案

  1. # 1 楼答案

    我看到两种选择:

    1. 如果要避免序列化获取的字段,请使用@JsonIgnore

    2. 如果根本不想获取这些字段,请创建DTO并编写自定义查询以将结果映射到该DTO:

      public class ProgramDTO {
      
          private Long id;
          private String programTitle;
          private String description;
          private String programType;
          private String price;
      
      }
      

      然后:

      entityManager
          .createQuery("select new ProgramDTO(p.id, p.programTitle, p.description, p.programType, p.price from Program p")
          .getResultList();